import { handleActions } from 'redux-actions'
import { CALL_API } from 'redux-api-middleware'
import { getApiFetchOptions } from 'nmb/util'
import MYT_AUTH from 'nmb/oauth2/MYT_AUTH'

// ------------------------------------
// Constants (Action Types)
// ------------------------------------
const REQUEST = 'REQUEST';
const REQUEST_FAILED = 'REQUEST_FAILED';

const GET_SUCCESS = 'GET_REQUEST';
const POST_SUCCESS = 'POST_SUCCESS';

// ------------------------------------
// Actions (Action Creator)
// ------------------------------------
export const getDemo = (message) => {
  const options = getApiFetchOptions(`util/get?message=${message}`);

  return {
    [CALL_API]: {
      [MYT_AUTH]: true,
      ...options,
      types: [
        REQUEST,
        {
          type: GET_SUCCESS,
          payload: (action, state, res) => {
            return {action, state, res};
          }
        },
        REQUEST_FAILED
      ]
    }
  }
};

export const getDemoWithoutAuth = (message) => {
  const options = getApiFetchOptions(`util/get-without-auth?message=${message}`);

  return {
    [CALL_API]: {
      ...options,
      types: [
        REQUEST,
        {
          type: GET_SUCCESS,
          payload: (action, state, res) => {
            return {action, state, res};
          }
        },
        REQUEST_FAILED
      ]
    }
  }
};

export const postDemo = () => {
  const options = getApiFetchOptions('util/post', 'POST');

  return {
    [CALL_API]: {
      [MYT_AUTH]: true,
      ...options,
      body: JSON.stringify({
        "post": "我突然想起来一个问题。   我拐子今天来上班冒，要找拐子抽根烟啊。"
      }),
      types: [
        REQUEST,
        {
          type: POST_SUCCESS,
          payload: (action, state, res) => {
            return {action, state, res};
          }
        },
        REQUEST_FAILED
      ]
    }
  }
};

export const actions = {
  getDemo,
  getDemoWithoutAuth,
  postDemo
};

// ------------------------------------
// Reducers
// ------------------------------------

const initialState = {
  result: '快去点按钮获取',
  pending: false
};

export default handleActions({

  [REQUEST] (state, { payload }) {
    return {...state, result: undefined, pending: true}
  },

  [REQUEST_FAILED] (state, { payload }) {
    return {...state, result: undefined, pending: false}
  },

  [GET_SUCCESS] (state, { payload }) {
    return {...state, result: JSON.stringify(payload), pending: false}
  },

  [POST_SUCCESS] (state, { payload }) {
    return {...state, result: JSON.stringify(payload), pending: false}
  },

}, initialState)